package com.ruoyi.report_tg.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.ruoyi.common.utils.BigDecimalUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.syrw.annotation.ComputeReportResult;
import com.ruoyi.syrw.annotation.FIllBasicInfo;
import com.ruoyi.syrw.annotation.FIllBasicInfoForTaiZhang;
import com.ruoyi.report_tg.domain.TgsybgBaDetail;
import com.ruoyi.report_tg.domain.vo.TgsybgBaDetailVo;
import com.ruoyi.report_tg.mapper.TgsybgBaDetailMapper;
import com.ruoyi.sycs.service.IBiQualificationService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.report_tg.domain.bo.TgsybgBsInfoBo;
import com.ruoyi.report_tg.domain.vo.TgsybgBsInfoVo;
import com.ruoyi.report_tg.domain.TgsybgBsInfo;
import com.ruoyi.report_tg.mapper.TgsybgBsInfoMapper;
import com.ruoyi.report_tg.service.ITgsybgBsInfoService;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 土工试验报告Service业务层处理
 *
 * @author zyb
 * @date 2024-05-24
 */
@RequiredArgsConstructor
@Service
@Transactional
public class TgsybgBsInfoServiceImpl implements ITgsybgBsInfoService {

    private final TgsybgBsInfoMapper baseMapper;
    private final TgsybgBaDetailMapper detailMapper;

    //    private static final Long[] keys = {"hsl", "md", "yx", "sx", "sxzs", "cd", "bz", "zdgmd", "zjhsl", "czb93", "pzl93"
//        , "czb94", "pzl94", "czb96", "pzl96",};
    private static final Long[] keys = {1L, 2L, 3L, 4L, 5L, 6L, 8L, 9L, 14L, 15L, 16L, 17L, 18L};

    private final IBiQualificationService biQualificationService;


    /**
     * 查询土工试验报告
     */
    @Override
    @FIllBasicInfo
    public TgsybgBsInfoVo queryById(Long excelId) {
        TgsybgBsInfoVo tgsybgBsInfoVo = baseMapper.selectVoById(excelId);
        // 查询detail
        List<TgsybgBaDetailVo> baDetailVos = detailMapper.selectVoList(new LambdaQueryWrapper<TgsybgBaDetail>()
            .eq(TgsybgBaDetail::getExcelId, excelId));
        baDetailVos.forEach(v->{
            v.setQualInfo(biQualificationService.queryById(v.getQualId()));
        });
        // 格式化 技术指标
        biQualificationService.compute(baDetailVos);
        // 转换成map形式
        Map<Long, TgsybgBaDetailVo> collect = baDetailVos.stream().collect(Collectors.toMap(TgsybgBaDetailVo::getQualId, v -> {
            return v;
        }));
        if (CollUtil.isNotEmpty(collect)) {
            tgsybgBsInfoVo.setBaDetailVos(collect);
        }
        // 生成报告结论
        // 如果已经有值了则不需要计算结论。
        if (StrUtil.isNotEmpty(tgsybgBsInfoVo.getJiancjl()) && !"检测结论：".equals(tgsybgBsInfoVo.getJiancjl())) {
            return tgsybgBsInfoVo;
        }
        return jcjl(tgsybgBsInfoVo);
    }

    @Override
    @FIllBasicInfoForTaiZhang
    public TgsybgBsInfoVo queryByIdForTaizhang(Long excelId) {
        TgsybgBsInfoVo tgsybgBsInfoVo = baseMapper.selectVoById(excelId);
        // 查询detail
        List<TgsybgBaDetailVo> baDetailVos = detailMapper.selectVoList(new LambdaQueryWrapper<TgsybgBaDetail>()
            .eq(TgsybgBaDetail::getExcelId, excelId));
        baDetailVos.forEach(v->{
            v.setQualInfo(biQualificationService.queryById(v.getQualId()));
        });
        // 格式化 技术指标
        biQualificationService.compute(baDetailVos);
        // 转换成map形式
        Map<Long, TgsybgBaDetailVo> collect = baDetailVos.stream().collect(Collectors.toMap(TgsybgBaDetailVo::getQualId, v -> {
            return v;
        }));
        if (CollUtil.isNotEmpty(collect)) {
            tgsybgBsInfoVo.setBaDetailVos(collect);
        }
        // 生成报告结论
        // 如果已经有值了则不需要计算结论。
        if (StrUtil.isNotEmpty(tgsybgBsInfoVo.getJiancjl()) && !"检测结论：".equals(tgsybgBsInfoVo.getJiancjl())) {
            return tgsybgBsInfoVo;
        }
        return jcjl(tgsybgBsInfoVo);
    }

    /**
     * 查询土工试验报告列表
     */
    @Override
    public TableDataInfo<TgsybgBsInfoVo> queryPageList(TgsybgBsInfoBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TgsybgBsInfo> lqw = buildQueryWrapper(bo);
        Page<TgsybgBsInfoVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询土工试验报告列表
     */
    @Override
    public List<TgsybgBsInfoVo> queryList(TgsybgBsInfoBo bo) {
        LambdaQueryWrapper<TgsybgBsInfo> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TgsybgBsInfo> buildQueryWrapper(TgsybgBsInfoBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TgsybgBsInfo> lqw = Wrappers.lambdaQuery();
//        lqw.eq(bo.getTotalPage() != null, TgsybgBsInfo::getTotalPage, bo.getTotalPage());
//        lqw.eq(bo.getPage() != null, TgsybgBsInfo::getPage, bo.getPage());
//        lqw.eq(StringUtils.isNotBlank(bo.getBaogbh()), TgsybgBsInfo::getBaogbh, bo.getBaogbh());
//        lqw.eq(StringUtils.isNotBlank(bo.getJiancdwmc()), TgsybgBsInfo::getJiancdwmc, bo.getJiancdwmc());
//        lqw.eq(StringUtils.isNotBlank(bo.getGongcbwyt()), TgsybgBsInfo::getGongcbwyt, bo.getGongcbwyt());
//        lqw.eq(StringUtils.isNotBlank(bo.getYangpmc()), TgsybgBsInfo::getYangpmc, bo.getYangpmc());
//        lqw.eq(StringUtils.isNotBlank(bo.getYangpbh()), TgsybgBsInfo::getYangpbh, bo.getYangpbh());
//        lqw.eq(StringUtils.isNotBlank(bo.getYangpsl()), TgsybgBsInfo::getYangpsl, bo.getYangpsl());
//        lqw.eq(StringUtils.isNotBlank(bo.getYangpzt()), TgsybgBsInfo::getYangpzt, bo.getYangpzt());
//        lqw.eq(bo.getYangpsj() != null, TgsybgBsInfo::getYangpsj, bo.getYangpsj());
//        lqw.eq(StringUtils.isNotBlank(bo.getJiancrq()), TgsybgBsInfo::getJiancrq, bo.getJiancrq());
//        lqw.eq(StringUtils.isNotBlank(bo.getShiytjwd()), TgsybgBsInfo::getShiytjwd, bo.getShiytjwd());
//        lqw.eq(StringUtils.isNotBlank(bo.getShiytjsd()), TgsybgBsInfo::getShiytjsd, bo.getShiytjsd());
//        lqw.eq(StringUtils.isNotBlank(bo.getJiancyj()), TgsybgBsInfo::getJiancyj, bo.getJiancyj());
//        lqw.eq(StringUtils.isNotBlank(bo.getPandyj()), TgsybgBsInfo::getPandyj, bo.getPandyj());
//        lqw.eq(StringUtils.isNotBlank(bo.getZhuyyqsbmcjbh()), TgsybgBsInfo::getZhuyyqsbmcjbh, bo.getZhuyyqsbmcjbh());
//        lqw.eq(StringUtils.isNotBlank(bo.getQuywz()), TgsybgBsInfo::getQuywz, bo.getQuywz());
//        lqw.eq(StringUtils.isNotBlank(bo.getWeitrwbh()), TgsybgBsInfo::getWeitrwbh, bo.getWeitrwbh());
//        lqw.eq(StringUtils.isNotBlank(bo.getTuycd()), TgsybgBsInfo::getTuycd, bo.getTuycd());
//        lqw.eq(StringUtils.isNotBlank(bo.getDaibsl()), TgsybgBsInfo::getDaibsl, bo.getDaibsl());
//        lqw.eq(StringUtils.isNotBlank(bo.getFujsm()), TgsybgBsInfo::getFujsm, bo.getFujsm());
//        lqw.eq(bo.getXiaoygkjzlbfs60() != null, TgsybgBsInfo::getXiaoygkjzlbfs60, bo.getXiaoygkjzlbfs60());
//        lqw.eq(bo.getXiaoygkjzlbfs40() != null, TgsybgBsInfo::getXiaoygkjzlbfs40, bo.getXiaoygkjzlbfs40());
//        lqw.eq(bo.getXiaoygkjzlbfs20() != null, TgsybgBsInfo::getXiaoygkjzlbfs20, bo.getXiaoygkjzlbfs20());
//        lqw.eq(bo.getXiaoygkjzlbfs10() != null, TgsybgBsInfo::getXiaoygkjzlbfs10, bo.getXiaoygkjzlbfs10());
//        lqw.eq(bo.getXiaoygkjzlbfs5() != null, TgsybgBsInfo::getXiaoygkjzlbfs5, bo.getXiaoygkjzlbfs5());
//        lqw.eq(bo.getXiaoygkjzlbfs2p0() != null, TgsybgBsInfo::getXiaoygkjzlbfs2p0, bo.getXiaoygkjzlbfs2p0());
//        lqw.eq(bo.getXiaoygkjzlbfs1p0() != null, TgsybgBsInfo::getXiaoygkjzlbfs1p0, bo.getXiaoygkjzlbfs1p0());
//        lqw.eq(bo.getXiaoygkjzlbfs0p5() != null, TgsybgBsInfo::getXiaoygkjzlbfs0p5, bo.getXiaoygkjzlbfs0p5());
//        lqw.eq(bo.getXiaoygkjzlbfs0p25() != null, TgsybgBsInfo::getXiaoygkjzlbfs0p25, bo.getXiaoygkjzlbfs0p25());
//        lqw.eq(bo.getXiaoygkjzlbfs0p075() != null, TgsybgBsInfo::getXiaoygkjzlbfs0p075, bo.getXiaoygkjzlbfs0p075());
//        lqw.eq(bo.getZhanztzlbfb2p0() != null, TgsybgBsInfo::getZhanztzlbfb2p0, bo.getZhanztzlbfb2p0());
//        lqw.eq(bo.getZhanztzlbfb1p0() != null, TgsybgBsInfo::getZhanztzlbfb1p0, bo.getZhanztzlbfb1p0());
//        lqw.eq(bo.getZhanztzlbfb0p5() != null, TgsybgBsInfo::getZhanztzlbfb0p5, bo.getZhanztzlbfb0p5());
//        lqw.eq(bo.getZhanztzlbfb0p25() != null, TgsybgBsInfo::getZhanztzlbfb0p25, bo.getZhanztzlbfb0p25());
//        lqw.eq(bo.getZhanztzlbfb0p075() != null, TgsybgBsInfo::getZhanztzlbfb0p075, bo.getZhanztzlbfb0p075());
//        lqw.eq(bo.getBujyxs() != null, TgsybgBsInfo::getBujyxs, bo.getBujyxs());
//        lqw.eq(bo.getQulxs() != null, TgsybgBsInfo::getQulxs, bo.getQulxs());
//        lqw.eq(StringUtils.isNotBlank(bo.getTuydmjdh()), TgsybgBsInfo::getTuydmjdh, bo.getTuydmjdh());
//        lqw.eq(StringUtils.isNotBlank(bo.getJiancjl()), TgsybgBsInfo::getJiancjl, bo.getJiancjl());
        return lqw;
    }

    /**
     * 新增土工试验报告
     */
    @Override
    @DSTransactional
    public Boolean insertByBo(TgsybgBsInfoBo bo) {
        TgsybgBsInfo add = BeanUtil.toBean(bo, TgsybgBsInfo.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setExcelId(add.getExcelId());
            // 新增详细 多个keys
            ArrayList<TgsybgBaDetail> details = new ArrayList<>(15);
            for (Long key : keys) {
                details.add(new TgsybgBaDetail(add.getExcelId(), key));
            }
            detailMapper.insertBatch(details);
        }
        return flag;
    }

    /**
     * 修改土工试验报告
     */
    @Override
    @DSTransactional
    @ComputeReportResult
    public Boolean updateByBo(TgsybgBsInfoBo bo) {
        // 增加对 是否合格 的填充
        fillExcelResult(bo);
        TgsybgBsInfo update = BeanUtil.toBean(bo, TgsybgBsInfo.class);
        validEntityBeforeSave(update);
        boolean flag = baseMapper.updateById(update) > 0;
        if (flag) {
            detailMapper.updateBatchById(BeanUtil.copyToList(bo.getBaDetailVos().values(), TgsybgBaDetail.class));
        }
        return flag;
    }

    private void fillExcelResult(TgsybgBsInfoBo bo) {
        if (CollUtil.isNotEmpty(bo.getBaDetailVos())) {
            for (TgsybgBaDetailVo detailVo : bo.getBaDetailVos().values()) {
                if ("不符合".equals(detailVo.getJiegpd())) {
                    bo.setExcelResult(2);
                    return;
                }
            }
            bo.setExcelResult(1);
            return;
        }
        bo.setExcelResult(0);
    }

    public boolean isWell(Long excelId) {
        return baseMapper.selectVoById(excelId).getExcelResult() != 2;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TgsybgBsInfo entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除土工试验报告
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 生成报告 检测结论
     */
    @Override
    public TgsybgBsInfoVo jcjl(TgsybgBsInfoVo vo) {
//        if (StrUtil.isEmpty(vo.getPandyj())) {
//            return vo;
//        }
        StringBuilder result = new StringBuilder("检测结论：经检测，该土样");
        boolean haveShicz = false;
        for (TgsybgBaDetailVo detailVo : vo.getBaDetailVos().values()) {
            if ("实测值".equals(detailVo.getJiegpd())) {
                result.append(detailVo.getQualName()).append("为").append(BigDecimalUtil.stpTrailZero(detailVo.getJiancjg())).append(detailVo.getQualUnit()).append("，");
                haveShicz = true;
            }
        }
        if (haveShicz) {
            result.append("其他指标符合");
        } else {
            result.append("所检指标符合");
        }
        result.append("JTG/T 3610-2019").append("《公路路基施工技术规范》及设计文件要求。");
        vo.setJiancjl(result.toString());
        return vo;
    }
}
